<?php
namespace App\Service;

class CryptService {

    /**
     * 加密数据
     *
     * @param $data string|array 需要加密的数据
     * @param $key string key
     * @param $iv string iv
     *
     * @return String
     */
    public function encrypt($data, string $key = null, string $iv = null)
    {
        $key    = $key ?? CRYPT['crypt_key'];
        $iv     = $iv ?? CRYPT['crypt_iv'];
        if (is_array($data)) $data = json_encode($data);
        return base64_encode(openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_PKCS1_PADDING, $iv));
    }

    /**
     * 解密数据
     *
     * @param $data string 需要解密的数据
     * @param $key string key
     * @param $iv string iv
     *
     * @return string
     */
    public function decrypt($data, string $key = null, string $iv = null)
    {
        $key    = $key ?? CRYPT['crypt_key'];
        $iv     = $iv ?? CRYPT['crypt_iv'];
        return openssl_decrypt(base64_decode($data), 'AES-128-CBC', $key, OPENSSL_PKCS1_PADDING, $iv);
    }
}
